#include"comm.hpp"

void Send()
{
    int fd = open(NAMED_PIPE, O_WRONLY);
    if(fd < 0)
    {
        perror("client open error");
        exit(1);
    }
    char buffer[1024];
    cout << "putin: ";
    fgets(buffer, sizeof(buffer)-1, stdin);
    write(fd, buffer, strlen(buffer));

    close(fd);
}


int main()
{
    key_t k = getKey();
    //printf("0x%x\n", k);

    //获取共享内存
    int shmid = GetShm(k);
    cout << "shmid: " << shmid << endl;

    // 共享内存与进程地址空间关联
    char* start = (char*)attachShm(shmid);

    // 通信，给server端发送数据
    const char* message = "hello, server, i'm client";
    pid_t id = getpid();
    int cnt = 1;
    while(1)
    {
        sleep(1);
        // 在共享内存中不在需要定义buffer，然后像管道那样read和write了。直接写给共享内存即可
        snprintf(start, SIZE, "%s[pid:%d][消息编号:%d]", message, id, cnt++);
        if(cnt == 5)
            break;
    }
    // 写完了就向命名管道内写一个数据让server端读取
    //向管道内写数据
    Send();

    //去关联
    sleep(5);
    detachShm(start);

    return 0;
}